﻿using Avalonia;
using Project2004.Jigsaw.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project2004.Jigsaw.Presenters
{
    public class BlockPresenterGroup
    {
        public List<BlockPresenter> Blocks { get; private set; } = new List<BlockPresenter>();

        internal readonly MainPresenter Parent;

        public BlockPresenterGroup(MainPresenter parent)
        {
            Parent = parent;
        }

        public LogicalGroup ToLogicalGroup()
        {
            var logicalGroup = new LogicalGroup();
            logicalGroup.Blocks = new List<BlockId>(Blocks.Select(i => i.Id));

            return logicalGroup;
        }

        public void SetPosition(BlockPresenter blockPresenter, Point position)
        {
            var baseId = blockPresenter.Id;
            var scene = Parent.Scene;

            foreach (var block in Blocks)
            {
                if (block == blockPresenter) continue;
                UpdatePosition(scene, baseId, position, block);
            }
            blockPresenter.Position = position;
        }

        private static void UpdatePosition(Scene scene, BlockId baseId, Point basePoint, BlockPresenter block)
        {
            var borderSize = scene.Size;

            var offsetX = (block.Id.X - baseId.X) * borderSize;
            var offsetY = (block.Id.Y - baseId.Y) * borderSize;
            var newPosition = basePoint + new Point(offsetX, offsetY);
            block.Position = newPosition;
        }

        public void UpdatePosition(BlockPresenter blockPresenter)
        {
            var position = blockPresenter.Position;
            SetPosition(blockPresenter, position);
        }
    }
}
